# app/main.py

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

from config.settings import settings
from app.api.upload.routes import router as upload_router
from app.api.rag.routes import router as rag_router
from app.api.kb.routes import router as kb_router
from app.api.common.responses import router as common_router
from app.core.logging import setup_logging
from app.api.celery_routes import router as celery_router  # 新增

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    setup_logging()
    
    # 初始化数据库连接和集合
    try:
        from app.core.database import connect_milvus, init_collections
        connect_milvus()
        init_collections()
        print("数据库初始化完成")
    except Exception as e:
        print(f"数据库初始化失败: {e}")
    
    print(f"{settings.PROJECT_NAME} v{settings.VERSION} 启动成功")
    
    yield
    
    # 关闭时执行
    print("应用正在关闭...")

# 创建FastAPI应用
app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    description="多模态RAG系统 - 支持文件上传和智能问答",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(upload_router, prefix="/api/v1/upload", tags=["文件上传"])
app.include_router(rag_router, prefix="/api/v1/rag", tags=["RAG问答"])
app.include_router(kb_router, prefix="/api/v1/kb", tags=["知识库管理"])
app.include_router(common_router, prefix="/api/v1", tags=["通用接口"])
app.include_router(celery_router, prefix="/api/v1/celery", tags=["Celery监控"])

@app.get("/")
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {settings.PROJECT_NAME}",
        "version": settings.VERSION,
        "docs": "/docs",
        "health": "/api/v1/health"
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host=settings.API_HOST,
        port=settings.UPLOAD_API_PORT,
        reload=settings.DEBUG
    ) 